import { useState, useEffect } from 'react'
import type { ThemeConfig } from 'antd'

// 从本地存储获取主题设置
const getStoredTheme = (): 'light' | 'dark' => {
  try {
    const stored = localStorage.getItem('theme')
    return stored === 'dark' ? 'dark' : 'light'
  } catch {
    return 'light'
  }
}

// 保存主题设置到本地存储
const setStoredTheme = (theme: 'light' | 'dark') => {
  try {
    localStorage.setItem('theme', theme)
  } catch (error) {
    console.error('Failed to save theme to localStorage:', error)
  }
}

export const useTheme = () => {
  const [theme, setTheme] = useState<'light' | 'dark'>(getStoredTheme())

  // 切换主题
  const toggleTheme = () => {
    const newTheme = theme === 'light' ? 'dark' : 'light'
    setTheme(newTheme)
    setStoredTheme(newTheme)
  }

  // 设置主题
  const setThemeMode = (newTheme: 'light' | 'dark') => {
    setTheme(newTheme)
    setStoredTheme(newTheme)
  }

  return {
    theme,
    toggleTheme,
    setThemeMode
  }
}